//分享页面
<template>
	<div>
		<view class="container" v-show="nowset"
			:style="{ height: contentHeight + 'px', display: 'flex', 'flex-direction': 'column' }">
			<uniNavBar :style="{paddingTop: systemBarHeight + 'px'}" height="65px" background-color="#dfdfdf"
				left-icon="left" leftText="取消" rightText="下一步" title="添加文章" @clickLeft="back" @clickRight="rightgo"/>
			<view class="page-body" :style="{ flex: 1 }">
				<view class='wrapper' :style="{ marginBottom: toolbarBottomMargin + 'px' }">
					<view class="editor-wrapper" style="padding: 1rem; overflow: auto;">
						<view class="uni-form-item uni-column">
							<input style="font-size: 1rem; font-weight: 800;" v-model="addpram.title" class="uni-input"
								placeholder="请输入标题(5~100字)" @focus="onInputtitleFocus" />
						</view>
						<editor ref="editorRef" id="editor" class="ql-container" placeholder="开始输入..." showImgSize
							showImgToolbar showImgResize @statuschange="onStatusChange" :read-only="readOnly"
							@ready="onEditorReady" @focus="onInputFocus" @click="offsel" />
					</view>
			
					<view class='toolbar' @tap="format" style="padding: 1rem 0;">
						<view class="addshuimg" @tap="insertImage">
							<image mode="aspectFit" :src="nowinput?iconurl.imgsel:iconurl.imgno"></image>
						</view>
						<view class="addshuimg" @click="gotoShare">
							<image mode="aspectFit" :src="nowinput?iconurl.documentsel:iconurl.documentno"></image>
						</view>
						<view class="addshuimg" @click="Totypeface">
							<image mode="aspectFit" :src="nowinput?iconurl.typefacesel:iconurl.typefaceno"></image>
						</view>
						<view class="addshuimg" @tap="undo">
							<image mode="aspectFit" :src="nowinput?iconurl.lastsel:iconurl.laseno"></image>
						</view>
						<view class="addshuimg" @tap="redo">
							<image mode="aspectFit" :src="nowinput?iconurl.nextsel:iconurl.nextno"></image>
						</view>
						<!-- 导航栏，点击进行操作或弹出 -->
						<!-- 	<view class="iconfont icon-charutupian" @tap="insertImage"></view>
					 <view class="addshuimg" @click="gotoShare"><image mode="aspectFit" :src="wenb"></image></view>
					  <view class="addshuimg" @click="gotoShare"><image mode="aspectFit" :src="paixu"></image></view>
					<view class="iconfont icon-undo" @tap="undo"></view>
					<view class="iconfont icon-redo" @tap="redo"></view> -->
						<!-- <view :class="formats.bold ? 'ql-active' : ''" class="iconfont icon-zitijiacu" data-name="bold">
					</view>
					<view :class="formats.italic ? 'ql-active' : ''" class="iconfont icon-zitixieti" data-name="italic">
					</view>
					<view :class="formats.underline ? 'ql-active' : ''" class="iconfont icon-zitixiahuaxian"
						data-name="underline"></view>
					<view :class="formats.strike ? 'ql-active' : ''" class="iconfont icon-zitishanchuxian"
						data-name="strike"></view>
					<view :class="formats.align === 'left' ? 'ql-active' : ''" class="iconfont icon-zuoduiqi"
						data-name="align" data-value="left"></view>
					<view :class="formats.align === 'center' ? 'ql-active' : ''" class="iconfont icon-juzhongduiqi"
						data-name="align" data-value="center"></view>
					<view :class="formats.align === 'right' ? 'ql-active' : ''" class="iconfont icon-youduiqi"
						data-name="align" data-value="right"></view>
					<view :class="formats.align === 'justify' ? 'ql-active' : ''" class="iconfont icon-zuoyouduiqi"
						data-name="align" data-value="justify"></view>
					<view :class="formats.lineHeight ? 'ql-active' : ''" class="iconfont icon-line-height"
						data-name="lineHeight" data-value="2"></view>
					<view :class="formats.letterSpacing ? 'ql-active' : ''" class="iconfont icon-Character-Spacing"
						data-name="letterSpacing" data-value="2em"></view>
					<view :class="formats.marginTop ? 'ql-active' : ''" class="iconfont icon-722bianjiqi_duanqianju"
						data-name="marginTop" data-value="20px"></view>
					<view :class="formats.previewarginBottom ? 'ql-active' : ''"
						class="iconfont icon-723bianjiqi_duanhouju" data-name="marginBottom" data-value="20px"></view>
					<view class="iconfont icon-clearedformat" @tap="removeFormat"></view>
					<view :class="formats.fontFamily ? 'ql-active' : ''" class="iconfont icon-font"
						data-name="fontFamily" data-value="Pacifico"></view>
					<view :class="formats.fontSize === '24px' ? 'ql-active' : ''" class="iconfont icon-fontsize"
						data-name="fontSize" data-value="24px"></view>

					<view :class="formats.color === '#0000ff' ? 'ql-active' : ''" class="iconfont icon-text_color"
						data-name="color" data-value="#0000ff"></view>
					<view :class="formats.backgroundColor === '#00ff00' ? 'ql-active' : ''"
						class="iconfont icon-fontbgcolor" data-name="backgroundColor" data-value="#00ff00"></view>

					<view class="iconfont icon-date" @tap="insertDate"></view>
					<view class="iconfont icon--checklist" data-name="list" data-value="check"></view>
					<view :class="formats.list === 'ordered' ? 'ql-active' : ''" class="iconfont icon-youxupailie"
						data-name="list" data-value="ordered"></view>
					<view :class="formats.list === 'bullet' ? 'ql-active' : ''" class="iconfont icon-wuxupailie"
						data-name="list" data-value="bullet"></view>
					

					<view class="iconfont icon-outdent" data-name="indent" data-value="-1"></view>
					<view class="iconfont icon-indent" data-name="indent" data-value="+1"></view>
					<view class="iconfont icon-fengexian" @tap="insertDivider"></view>
					
					<view :class="formats.header === 1 ? 'ql-active' : ''" class="iconfont icon-format-header-1"
						data-name="header" :data-value="1"></view>
					<view :class="formats.script === 'sub' ? 'ql-active' : ''" class="iconfont icon-zitixiabiao"
						data-name="script" data-value="sub"></view>
					<view :class="formats.script === 'super' ? 'ql-active' : ''" class="iconfont icon-zitishangbiao"
						data-name="script" data-value="super"></view>
					<view class="iconfont icon-shanchu" @tap="clear"></view>
					<view :class="formats.direction === 'rtl' ? 'ql-active' : ''" class="iconfont icon-direction-rtl"
						data-name="direction" data-value="rtl"></view> -->
					</view>
					<view @tap="format" ref="aatext" class="aatextcon"
						:style="{height: height,display: isShown ? 'block' : 'none'}">
						<view class="title">文本格式</view>
						<view class="chooseone">
							<view :class="formats.bold ? 'ql-active' : ''" class="iconfont icon-zitijiacu"
								data-name="bold">
							</view>
							<view :class="formats.italic ? 'ql-active' : ''" class="iconfont icon-zitixieti"
								data-name="italic">
							</view>
							<view :class="formats.underline ? 'ql-active' : ''" class="iconfont icon-zitixiahuaxian"
								data-name="underline"></view>
							<view :class="formats.strike ? 'ql-active' : ''" class="iconfont icon-zitishanchuxian"
								data-name="strike"></view>
						</view>
						<view class="title">对齐方式</view>
						<view class="chooseone">
							<view :class="formats.align === 'left' ? 'ql-active' : ''" class="iconfont icon-zuoduiqi"
								data-name="align" data-value="left"></view>
							<view :class="formats.align === 'center' ? 'ql-active' : ''"
								class="iconfont icon-juzhongduiqi" data-name="align" data-value="center"></view>
							<view :class="formats.align === 'right' ? 'ql-active' : ''" class="iconfont icon-youduiqi"
								data-name="align" data-value="right"></view>
							<view :class="formats.align === 'justify' ? 'ql-active' : ''"
								class="iconfont icon-zuoyouduiqi" data-name="align" data-value="justify"></view>
						</view>
					</view>
					<view @tap="format" ref="typeface" class="aatextcon"
						:style="{height: height,display: isShownoe ? 'block' : 'none'}">
						<view class="title">排序方式</view>
						<view class="chooseone">
							<view class="iconfont icon--checklist" data-name="list" data-value="check"></view>
							<view :class="formats.list === 'ordered' ? 'ql-active' : ''"
								class="iconfont icon-youxupailie" data-name="list" data-value="ordered"></view>
							<view :class="formats.list === 'bullet' ? 'ql-active' : ''" class="iconfont icon-wuxupailie"
								data-name="list" data-value="bullet"></view>
						</view>
						<view class="title">字体</view>
						<view class="chooseone">
							<view :class="formats.fontSize === '24px' ? 'ql-active' : ''" class="iconfont icon-fontsize"
								data-name="fontSize" data-value="24px"></view>
							<view :class="formats.color === '#0000ff' ? 'ql-active' : ''"
								class="iconfont icon-text_color" data-name="color" data-value="#0000ff"></view>
							<view :class="formats.backgroundColor === '#00ff00' ? 'ql-active' : ''"
								class="iconfont icon-fontbgcolor" data-name="backgroundColor" data-value="#00ff00">
							</view>

						</view>
					</view>
				</view>
			</view>

		</view>
		<view v-show ="!nowset">
			<uniNavBar :style="{paddingTop: systemBarHeight + 'px'}" height="65px" background-color="#dfdfdf"
				left-icon="left" leftText="取消"  title="设置" @clickLeft="backset" />
						<button class="publishbu" @click="getEditorContent">发布</button>
		</view>
	</div>
</template>

<script>
	import uploadurl from "@/config/index.js"
	import {
		adduserarticle
	} from '@/request/setarticle.js'
	import uniNavBar from '@/uni_modules/uni-nav-bar/components/uni-nav-bar/uni-nav-bar.vue'
	export default {
		data() {
			return {
				nowset: true,
				isShownoe: false,
				isShown: false, // 控制是否显示
				canUndo: false,
				canRedo: false,
				iconurl: {
					documentno: require('@/static/textincon/documentno.png'),
					documentsel: require('@/static/textincon/documentsel.png'),
					imgno: require('@/static/textincon/imgno.png'),
					imgsel: require('@/static/textincon/imgsel.png'),
					laseno: require('@/static/textincon/laseno.png'),
					lastsel: require('@/static/textincon/lastsel.png'),
					nextno: require('@/static/textincon/nextno.png'),
					nextsel: require('@/static/textincon/nextsel.png'),
					typefaceno: require('@/static/textincon/typefaceno.png'),
					typefacesel: require('@/static/textincon/typefacesel.png')
				},
				//判断富文本编辑框是否聚焦
				nowinput: false,
				height: '10rem',
				systemBarHeight: 0,
				contentHeight: 0,
				toolbarBottomMargin: 0,
				systemBarHeight: 0,
				readOnly: false,
				formats: {},
				editorContent: '',
				serverurl: [],
				addpram: {
					id: uni.getStorageSync('id'),
					title: "",
					createtime: '',
					createname: this.$store.state.nickname==null? '':this.$store.state.nickname,
					code: '',
					runimg: ''
				}
			}
		},
		// onLoad() {
		//    this.systemBarHeight = uni.getSystemInfoSync().statusBarHeight;
		//    this.contentHeight = uni.getSystemInfoSync().windowHeight;
		//    // uni.onKeyboardHeightChange(this.onKeyboardHeightChange);
		// // uni.onKeyboardHeightChange(res => {
		// // 			  console.log(res,'键盘弹出')
		// // 			})
		//  },
		components: {
			uniNavBar
		},
		created() {
			this.systemBarHeight = uni.getSystemInfoSync().statusBarHeight;
			this.contentHeight = uni.getSystemInfoSync().windowHeight;
			uni.onKeyboardHeightChange(this.onKeyboardHeightChange);
		},
		methods: {
			gotoShare() {
				if (this.isShownoe) {
					this.isShownoe = false
					this.isShown = true
				} else if (this.isShown) {
					this.isShown = false
					this.height = '0rem'; // 或者任何你需要的高度
				} else {
					this.isShown = true
					this.height = '10rem'; // 或者任何你需要的高度
				}

			},
			Totypeface() {
				if (this.isShown) {
					this.isShown = false
					this.isShownoe = true
				} else if (this.isShownoe) {
					this.isShownoe = false
					this.height = '0rem'; // 或者任何你需要的高度
				} else {
					this.isShownoe = true
					this.height = '10rem'; // 或者任何你需要的高度
				}

			},
			onInputtitleFocus(e) {
				this.nowinput = false
				// 标题输入框聚焦
				this.toolbarBottomMargin = e.detail.height;
				this.isShown = false
				this.isShownoe = false
				this.height = '0rem'; // 或者任何你需要的高度 
			},
			offsel() {
				this.isShown = false
				this.isShownoe = false
				this.height = '0rem'; // 或者任何你需要的高度 
			},
			onInputFocus(e) {
				if (this.isShown) {
					uni.hideKeyboard()
				} else {
					this.nowinput = true
					// 当输入框获得焦点时，调整工具栏的位置
					this.toolbarBottomMargin = e.detail.height;
				}

			},
			onKeyboardHeightChange(e) {
				const keyboardHeight = e.height;
				const windowHeight = uni.getSystemInfoSync().windowHeight;

				if (keyboardHeight > 0) {
					// 键盘弹出
					this.contentHeight = windowHeight - keyboardHeight;
					this.toolbarBottomMargin = keyboardHeight;
				} else {
					// 键盘收回
					this.contentHeight = windowHeight;
					this.toolbarBottomMargin = 0;
				}
			},
			getSysteminfo() {
				uni.getSystemInfo({
					success: res => {
						this.systemBarHeight = res.statusBarHeight + 10;
					}
				});
			},
			//返回文章编辑
			backset(){
				this.nowset=true
			},
			//跳转到发布页面
			rightgo(){
				this.nowset=false
			},
			back() {
				uni.navigateBack({
					delta: 1
				})
			},
			getContentsPromise(editorCtx) {
				return new Promise((resolve, reject) => {
					editorCtx.getContents({
						success: function(res) {
							resolve(res.html);
						},
						fail: function(err) {
							reject(err);
						}
					});
				});
			},
			async getEditorContent() {
				try {
					// 获取 HTML 内容
					this.editorContent = await this.getContentsPromise(this.editorCtx);
					console.log(this.editorContent,'shuju ')
					const images = [];
					// 获取所有html中所有的图片
					const imgElements = this.editorContent.match(/<img[^>]+src=["']([^"']+)["'][^>]*>/g);
					if (imgElements) {
						imgElements.forEach(imgElement => {
							const srcMatch = imgElement.match(/src=["']([^"']+)["']/);
							if (srcMatch && srcMatch[1]) {
								images.push(srcMatch[1]);
							}
						});
					}

					this.sendBlobsToServer(images).then((e) => {
						this.replaceImgSrcInHtml(this.editorContent, this.serverurl).then((htm) => {
							//将dom节点传给后端，并保存
							// 获取当前时间

							if (this.serverurl.length !== 0) {

								this.addpram.runimg = this.serverurl[0]
							}
							const now = new Date();

							// 格式化日期和时间
							const formattedDate =
								`${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')}`;
							const formattedTime =
								`${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')}`;
							this.addpram.code = htm
							this.addpram.createtime = `${formattedDate} ${formattedTime}`
							//向后端发送请求
							adduserarticle(this.addpram).then((e)=>{
								uni.showToast({
									title: '发布成功',
									icon: 'none',
									duration: 2000
								})
								uni.reLaunch({
									url: '/pages/home/index' // 注意路径格式  
								});
							})
						})
					})
					// 接下来，你可以上传这些内容和图片到你的服务器


				} catch (error) {

					console.error('Error getting editor content:', error);
				}
			},
			//替换html中的img地址
			async replaceImgSrcInHtml(htmlContent, localPaths) {
				// 使用正则表达式匹配所有的<img>标签
				const imgRegex = /<img\s+[^>]*src\s*=\s*["']([^"']*)["'][^>]*data-local\s*=\s*["']([^"']*)["'][^>]*>/g;
				let match;
				let updatedHtml = htmlContent;
				let index = 0;

				while ((match = imgRegex.exec(htmlContent)) !== null) {
					// 获取当前img标签的src属性值
					const currentSrc = match[1];
					const dataLocal = match[2]; // 这里只是获取data-local的值，我们不需要使用它

					// 检查是否还有可用的本地路径
					if (index < localPaths.length) {
						// 替换当前img标签的src属性值，并移除data-local属性
						const newSrc = `${localPaths[index].split('\\').pop()}`;
						const replacement = `<img src="${newSrc}" alt="图像">`; // 只保留src和alt属性
						updatedHtml = updatedHtml.replace(match[0], replacement);

						// 移动到下一个本地路径
						index++;
					}
				}

				return updatedHtml;
			},
			//判断后缀名
			async getMimeType(blobUrl) {
				const mimeTypeToExtensionMap = {
					'image/png': '.png',
					'image/jpeg': '.jpg',
					'image/jpg': '.jpg',
					'image/gif': '.gif',
					'application/pdf': '.pdf',
					// 可以添加更多映射关系
				};
				// 使用 fetch API 获取 Blob 数据
				const response = await fetch(blobUrl);
				const blob = await response.blob();

				// 获取 Blob 的 MIME 类型
				const mimeType = blob.type;
				return mimeTypeToExtensionMap[mimeType] || 'unknown'; 
			},
			//提交图片
			async sendBlobsToServer(blobUrls) {
				const self = this; // 保存 this 的引用
				for (const url of blobUrls) {
					try {
						//#ifdef APP-PLUS
						await new Promise((resolve, reject) => {
							uni.uploadFile({
								url: `${uploadurl.baseUrl}/upload`, // 服务器上传接口地址
								filePath: url, // 本地文件路径
								name: 'image', // 服务器接收文件的字段名
								formData: {}, // 其他需要上传的数据
								success: function(res) {
									const responseObject = JSON.parse(res.data);
									this.serverurl.push(responseObject.data.imgurl);
									resolve(); // 当成功上传时解析 Promise
								}.bind(this), // 绑定 `this` 到当前上下文
								fail: function(err) {
									console.error('Error uploading file:', err);
									reject(err); // 当失败时拒绝 Promise
								}
							});
						});
						// #endif
						// #ifdef H5
						let hc = await this.getMimeType(url)
						const response = await fetch(url);
						const blob = await response.blob();

						// 创建 FormData 对象
						const formData = new FormData();
						formData.append('image', blob, hc); // 第二个参数是 Blob 对象，第三个参数是文件名

						// 发送 POST 请求到你的后端路由
						const result = await fetch(`${uploadurl.baseUrl}/upload`, {
							headers: {
								"Authorization": uni.getStorageSync('token')
							},
							method: 'POST',
							body: formData
						})

						if (!result.ok) {
							throw new Error(`Failed to upload image: ${result.status} ${result.statusText}`);
						}

						const data = await result.json();
						this.serverurl.push(data.data.imgurl)
						// #endif
					} catch (error) {
						console.error('Error uploading image:', error);
					}
				}
			},

			readOnlyChange() {
				this.readOnly = !this.readOnly
			},
			onEditorReady(editor) {

				// this.editorCtx = editor;
				uni.createSelectorQuery().select('#editor').context((res) => {
					this.editorCtx = res.context
				}).exec()
			},
			undo() {
				if (this.nowinput) {
					this.editorCtx.undo()
				}

			},
			redo() {
				if (this.nowinput) {
					this.editorCtx.redo()
				}
			},
			format(e) {
				let {
					name,
					value
				} = e.target.dataset
				if (!name) return
				// console.log('format', name, value)
				this.editorCtx.format(name, value)

			},
			onStatusChange(e) {
				const formats = e.detail
				this.formats = formats
			},
			insertDivider() {
				this.editorCtx.insertDivider({
					success: function() {
						console.log('insert divider success')
					}
				})
			},
			clear() {
				this.editorCtx.clear({
					success: function(res) {
						console.log("clear success")
					}
				})
			},
			removeFormat() {
				this.editorCtx.removeFormat()
			},
			insertDate() {
				const date = new Date()
				const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
				this.editorCtx.insertText({
					text: formatDate
				})
			},
			insertImage() {
				if (this.nowinput) {
					uni.chooseImage({
						count: 1,
						success: (res) => {
							this.editorCtx.insertImage({
								src: res.tempFilePaths[0],
								alt: '图像',
								success: function() {
									console.log('insert image success')
								}
							})
						}
					})
				}
			}
		},
		onLoad() {
			// uni.loadFontFace({
			// 	family: 'Pacifico',
			// 	source: 'url("https://sungd.github.io/Pacifico.ttf")'
			// })
		},
	}
</script>

<style>
	@import "./editor-icon.css";

	uni-view {
		border-bottom: 0px !important;

	}

	.uni-navbar {
		background: #dfdfdf;
	}

	.page-body {
		overflow: hidden;
		flex-grow: 1;
	}

	.wrapper {
		display: flex;
		flex-direction: column;
		height: 100%;
	}

	.editor-wrapper {
		padding: 1rem;
		overflow: auto;
		flex-grow: 1;
		background: #fff;
	}

	.iconfont {
		display: inline-block;
		padding: 8px 8px;
		width: 24px;
		height: 24px;
		cursor: pointer;
		font-size: 20px;
	}

	.toolbar {
		display: flex;
		align-items: center;
		justify-content: space-evenly;
		height: 3rem;
		margin-bottom: 0.1rem;
		border-top: 1px solid #cccccc;
		border-bottom: 1px solid #cccccc !important;
		box-sizing: border-box;
		border-bottom: 0;
		font-family: 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif;
	}


	.ql-container {
		box-sizing: border-box;
		padding: 12px 15px;
		width: 100%;
		/* min-height: 30vh; */
		margin-top: 20px;
		font-size: 16px;
		height: auto !important;
	}

	.ql-active {
		color: #06c;
	}
</style>
<style lang="less" scoped>
	.publishbu{
		margin-top: 40px;
		background-color: #fb5432;
		    width: 7rem;
		    height: 3rem;
			color: #fff;
	}
	.addshuimg {
		display: flex;
		flex-direction: row-reverse;
		align-items: center;

		uni-image {
			width: 1.7rem !important;
			height: 1.7rem !important;
		}
	}

	.aatextcon {

		// height: 10rem;
		display: none;
		height: 0rem;
		padding: 2rem;
		margin-bottom: 3rem;

		.title {
			font-size: 0.7rem;
			color: #999696;
		}

		.chooseone {
			padding: 0.2rem 1rem;
			display: flex;
			justify-content: space-evenly;
			background: #f7f7f7;
			border-radius: 0.4rem;
			margin: 1rem 0;
		}
	}
</style>